<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef">
      <template #billTypeSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择单据类型" readonly @search="billTypeOpen" />
      </template>
      <template #currencySlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择币种" readonly @search="open" />
      </template>
      <template #customerSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择客户名称" readonly @search="openCustomer" />
      </template>
      <template #organizationSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择接单组织" readonly @search="openOrganization" />
      </template>
      <template #paymentConditionSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择付款条件" readonly @search="openPaymentCondition(1)" />
      </template>
      <template #accountConditionSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择立账条件" readonly @search="openPaymentCondition(2)" />
      </template>
      <template #shippingPrincipleSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择出货原则" readonly @search="openPaymentCondition(3)" />
      </template>
      <template #warehouseSlot="{ model, field }">
        <a-input-search v-model:value="model[field]" placeholder="请选择存储地址" readonly @search="openWarehouse" />
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="销售订单明细" key="busSaleOrderItem" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="busSaleOrderItem"
          :loading="busSaleOrderItemTable.loading"
          :columns="busSaleOrderItemTable.columns"
          :dataSource="busSaleOrderItemTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
          :disabled="formDisabled"
          :toolbar="true"
        >
          <template #action="props">
            <a-input-search @click="handleView(props)" placeholder="请选择料品编号" readonly v-model:value="props.row.materialCode"></a-input-search>
          </template>
          <template #organizationSlot="props">
            <a-input
              @click="organizationHandleView(props)"
              placeholder="请选择业务组织名称"
              readonly
              v-model:value="props.row.businessOrganizationName"
            ></a-input>
          </template>
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 币种 -->
  <currencySelectModel @register="regModal" @getSelectResult="handleSuccess" v-bind="getBindValue"></currencySelectModel>
  <!-- 客户 -->
  <customerSelectModel @register="customerRegModal" @getSelectResult="customerHandleSuccess" v-bind="getBindValue"></customerSelectModel>
  <!-- 接单组织 -->
  <organizationSelectModel
    @register="organizationRegModal"
    @getSelectResult="organizationHandleSuccess"
    v-bind="getBindValue"
  ></organizationSelectModel>
  <!-- 条件 -->
  <paymentConditionSelectModel
    @register="paymentConditionRegModal"
    @getSelectResult="paymentConditionHandleSuccess"
    v-bind="getBindValue"
  ></paymentConditionSelectModel>
  <!-- 料品 -->
  <materialSelectModel @register="materialRegModal" @getSelectResult="materialhandleSuccess" v-bind="getBindValue"></materialSelectModel>
  <!-- 单据类型 -->
  <billTypeSelectModel @register="billTypeRegModal" @getSelectResult="billTypehandleSuccess" v-bind="getBindValue"></billTypeSelectModel>
  <!-- 仓库 -->
  <warehouseSelectModel @register="warehouseRegModal" @getSelectResult="warehousehandleSuccess" v-bind="getBindValue"></warehouseSelectModel>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
import { formSchema, busSaleOrderItemColumns } from '../BusSaleShipment.data';
import { saveOrUpdate, busSaleOrderItemList } from '../BusSaleShipment.api';
import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
import currencySelectModel from './currencySelectModel.vue';
import customerSelectModel from './customerSelectModel.vue';
import organizationSelectModel from './organizationSelectModel.vue';
import paymentConditionSelectModel from './paymentConditionSelectModel.vue';
import materialSelectModel from './materialSelectModel.vue';
import billTypeSelectModel from '/@/views/components/billTypeSelectModel.vue';
import warehouseSelectModel from './warehouseSelectModel.vue';

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const formDisabled = ref(false);
const refKeys = ref(['busSaleOrderItem']);
const activeKey = ref('busSaleOrderItem');
const busSaleOrderItem = ref();
const tableRefs = { busSaleOrderItem };
const busSaleOrderItemTable = reactive({
  loading: false,
  dataSource: [],
  columns: busSaleOrderItemColumns,
});
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  labelWidth: 150,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await reset();
  setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  formDisabled.value = !data?.showFooter;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(busSaleOrderItemList, { id: data?.record?.id }, busSaleOrderItemTable);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});

//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);
const [regModal, { openModal }] = useModal();
const [billTypeRegModal, { openModal: openBillTypeModal }] = useModal();
const [customerRegModal, { openModal: openCustomerModal }] = useModal();
const [organizationRegModal, { openModal: openOrganizationModal }] = useModal();
const [paymentConditionRegModal, { openModal: openPaymentConditionModal }] = useModal();
const [materialRegModal, { openModal: openMaterialModal }] = useModal();
const [unitRegModal, { openModal: openUnitModal }] = useModal();
const [warehouseRegModal, { openModal: openwarehouseModal }] = useModal();

//单据类型
function billTypeOpen() {
  openBillTypeModal(true, {
    isUpdate: false,
    showFooter: true,
    tableName:"bus_sale_shipment"
  });
}
//打开选择币种
function open() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择客户
function openCustomer() {
  openCustomerModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择销售组织
function openOrganization() {
  openOrganizationModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择条件
function openPaymentCondition(type) {
  openPaymentConditionModal(true, {
    isUpdate: false,
    showFooter: true,
    type: type,
  });
}
let index: number | null = null;
//打开选择料品
function handleView(props) {
  index = props.params.$rowIndex;
  openMaterialModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开业务组织
function organizationHandleView(props) {
  index = props.params.$rowIndex;
  openOrganizationModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开仓库
function openWarehouse() {
  openwarehouseModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
const getBindValue = Object.assign({}, '');
//币种选择回写
function handleSuccess(val, values) {
  setFieldsValue({
    currencyName: val[0].label,
    currencyId: val[0].value,
  });
}
//客户选择回写
function customerHandleSuccess(val, values) {
  setFieldsValue({
    customerName: val[0].label,
    customerId: val[0].value,
  });
}
//客户选择回写
function organizationHandleSuccess(val, values) {
  setFieldsValue({
    shippingOrganizationName: val[0].label,
    shippingOrganizationId: val[0].value,
  });
  if (index != null) {
    busSaleOrderItemTable.dataSource = busSaleOrderItem.value!.getTableData();
    busSaleOrderItemTable.dataSource[index].businessOrganizationName = val[0].label;
    busSaleOrderItemTable.dataSource[index].businessOrganizationId = val[0].value;
  }
}
//条件选择回写
function paymentConditionHandleSuccess(val, values, type) {
  if (type == 1) {
    setFieldsValue({
      paymentConditionName: val[0].label,
      paymentConditionId: val[0].value,
    });
  } else if (type == 2) {
    setFieldsValue({
      accountConditionName: val[0].label,
      accountConditionId: val[0].value,
    });
  } else if (type == 3) {
    setFieldsValue({
      shippingPrincipleName: val[0].label,
      shippingPrincipleId: val[0].value,
    });
  }
}
//料品回写
function materialhandleSuccess(val, values) {
  busSaleOrderItemTable.dataSource = busSaleOrderItem.value!.getTableData();
  busSaleOrderItemTable.dataSource[index].materialName = val[0].label;
  busSaleOrderItemTable.dataSource[index].materialId = val[0].value;
  busSaleOrderItemTable.dataSource[index].materialCode = val[0].item.code;
  // 自动带出单位
  busSaleOrderItemTable.dataSource[index].unitId = val[0].item.stockUnitId;
  busSaleOrderItemTable.dataSource[index].unitName = val[0].item.stockUnitName;
}
//单据类型回写
function billTypehandleSuccess(val, values) {
  setFieldsValue({
    billTypeName: val[0].label,
    billTypeId: val[0].value,
  });
}
//仓库回写
function warehousehandleSuccess(val, values) {
  setFieldsValue({
    warehouseName: val[0].label,
    warehouseId: val[0].value,
  });
}
//设置标题
const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

async function reset() {
  await resetFields();
  activeKey.value = 'busSaleOrderItem';
  busSaleOrderItemTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    busSaleOrderItemList: allValues.tablesValue[0].tableData,
  };
}
//表单提交事件
async function requestAddOrEdit(values) {
  try {
    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>